package com.kangfuqiang.util;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kangfuqiang.exception.ConfigurationException;

/**
 * @Description: 系统参数实用类
 * @author kangfuqiang
 */
public class SysParamsUtil {
	static Logger				log				= LoggerFactory.getLogger(SysParamsUtil.class);

	/** 系统参数配置文件相对类路径 */
	private static final String	SYS_PARAMS_PATH	= "sysParams.properties";

	/** 系统参数配置File */
	private static File			sysParamsFile	= ResourceUtil.getResourceAsFile(SYS_PARAMS_PATH);

	private static long			lastModified;

	private static Properties	properties;

	static {
		loadProperties();//初次加载
	}

	public static String getValue(String key) {
		reloadPropertiesIfModify();
		return properties.getProperty(key);
	}

	public static String getValue(String key, String defaultValue) {
		reloadPropertiesIfModify();
		return properties.getProperty(key, defaultValue);
	}

	public static int getIntValue(String key) {
		reloadPropertiesIfModify();
		return Integer.parseInt(properties.getProperty(key));
	}

	public static int getIntValue(String key, int defaultIntValue) {
		reloadPropertiesIfModify();
		return Integer.parseInt(properties.getProperty(key, String.valueOf(defaultIntValue)));
	}

	public static void printKeyAndValue() {
		reloadPropertiesIfModify();
		System.out.println(properties);
	}

	/** 如果“系统参数配置文件”已改变，则重新加载Properties */
	private static void reloadPropertiesIfModify() {
		if (lastModified != sysParamsFile.lastModified()) {
			log.debug("configuation file[{}] has changed!", SYS_PARAMS_PATH);
			log.debug("lastModified: {}---->{}", DateUtil.formatDate(lastModified), DateUtil
					.formatDate(sysParamsFile.lastModified()));
			loadProperties();
		}
	}

	/** 加载Properties */
	private static void loadProperties() {
		try {
			lastModified = sysParamsFile.lastModified();
			properties = new Properties();
			FileInputStream fis = new FileInputStream(sysParamsFile);
			properties.load(fis);
			fis.close();
			log.debug("successfully loaded configuation file[{}]", SYS_PARAMS_PATH);
		} catch (Exception e) {
			log.warn("NOT FOUND sysParameters.property FILE!", e);
			throw new ConfigurationException("NOT FOUND sysParameters.property FILE!", e);
		}
	}

	public static void main(String[] args) throws InterruptedException {
		for (int i = 0; i < 20; i++) {
			System.out.println(i + "  sleep(5000)...");
			Thread.sleep(5000);
			System.out.println(getValue(("exam_server_ip")));
		}
	}
}
